<!-- src/views/dashboard/BarChart.vue -->
<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    console.log('BarChart', this.chartData)
    this.$nextTick(() => {
      this.initChart();
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions(data) {
      this.chart.setOption({
        tooltip: {
          trigger: 'item', // 鼠标悬停时触发
          formatter: '{b}: {c}' // 显示格式，{b}为类别，{c}为数值
        },
        grid: {
          left: 10, // 左边距
          right: 10, // 右边距
          bottom: 20, // 下边距
          top: 30, // 上边距
          containLabel: true // 包含标签
        },
        xAxis: {
          type: 'category',
          data: data.xAxis,
          axisLabel: {
            interval: 0, // 显示所有标签
            rotate: 30 // 旋转标签以适应更多数据
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '人数',
          type: 'bar',
          data: data.series,
          itemStyle: {
            color: '#3888fa'
          },
          barWidth: '10%', // 调整柱子的宽度
          label: {
            show: true, // 显示标签
            position: 'top', // 标签位置
            formatter: '{c}' // 标签格式
          }
        }]
      })
    }
  }
}
</script>